//
//  AudioExampleAppDelegate.m
//  Google Ads iPhone publisher SDK.
//
//  Copyright Google Inc 2009. All rights reserved.
//
//  This application demonstrates using the Google Ads iPhone publisher SDK
//  to play audio ads.
//
//  It plays a (short) song and then plays a test audio ad. While the song is
//  playing, the title and artist are also shown.  While the ad is playing,
//  the title and artist are hidden.  When the ad finishes, the song plays
//  again.  The image is shown for several seconds after the ad plays, in order
//  to provide additional time for the user to click on the ad.

#import <AudioToolbox/AudioToolbox.h>

#import "AudioExampleAppDelegate.h"

@implementation AudioExampleAppDelegate

@synthesize window = window_;
@synthesize mainViewController = mainViewController_;
@synthesize nowPlayingText = nowPlayingText_;

- (void)loadAd {
  adLoaded_ = NO;
  adLoadFailed_ = NO;
  [adViewController_.view setHidden:YES];  // Don't show  while loading.

  NSString *rockChannel = @"rock_music";
  // Replace the following test values with your own.
  NSString *testClientId = @"ca-audio-pub-0941106809233305";
  NSString *testUrl = @"www.onlineaudioadstest.com";
  NSString *testAppName = @"myApp";
  NSString *testCompany = @"Acme Corp.";
  NSString *testApplicationAppleID = @"0";  // NOTE: For testing only
  NSString *testAudioTitle = @"Nine To Life";
  NSString *testAudioArtist = @"No More Heroes";
  NSString *testAudioDescription = @"Irish rock music";
  NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
      testClientId, kGADAdSenseClientID,
      [NSArray arrayWithObjects:rockChannel, nil], kGADAdSenseChannelIDs,
      [NSNumber numberWithInt:1], kGADAdSenseIsTestAdRequest,
      kGADAdSenseAudioImageAdType, kGADAdSenseAdType,
      [NSNumber numberWithInt:30000], kGADAdSenseMaxDuration,
      testAppName, kGADAdSenseAppName,
      testCompany, kGADAdSenseCompanyName,
      testApplicationAppleID, kGADAdSenseApplicationAppleID,
      testUrl, kGADAdSenseAppWebContentURL,
      testAudioArtist, kGADAdSenseAudioArtist,
      testAudioTitle, kGADAdSenseAudioTitle,
      testAudioDescription, kGADAdSenseAudioDescription,
      nil];
  // We will receive -loadSucceeded:withResults: call when the load completes
  [adViewController_ loadGoogleAd:attributes];
  NSLog(@"loading ad");
}

- (void)playSong {
  [[self nowPlayingText] setHidden:NO];
  songDone_ = NO;  // When song is done, we'll play the ad.
  [audioPlayer_ play];

  NSTimeInterval timeToLeavePreviousBannerUp = 5.0;
  // Wait before beginning to load the next ad to allow
  // the user to react to the previous ad (if present).
  [self performSelector:@selector(loadAd)
             withObject:nil
             afterDelay:timeToLeavePreviousBannerUp];
}

- (void)setUpSong {
  audioPlayer_ = [AVAudioPlayer alloc] ;
  NSString *songName = @"NineToLife.mp3";
  NSURL *audioFile = [NSURL fileURLWithPath:
      [[NSBundle mainBundle] pathForResource:songName ofType:@""]];
  NSError *error;
  [audioPlayer_ initWithContentsOfURL:audioFile error:&error];
  [audioPlayer_ setDelegate:self];

}

- (void)applicationDidFinishLaunching:(UIApplication*)application {
  UIView *mainView = [mainViewController_ view];
  [window_ addSubview:mainView];

  adViewController_ = [[GADAdViewController alloc] initWithDelegate:self];
  [adViewController_ setAdSize:kGADAdSize320x50];

  // Position ad at bottom of screen.
  CGFloat adViewHeight = [adViewController_ adSize].height;
  CGRect bounds = [mainView bounds];
  CGPoint center = CGPointMake(CGRectGetMidX(bounds),
                               CGRectGetMaxY(bounds) - adViewHeight / 2);

  UIView *adView = [adViewController_ view];

  [self setUpSong];
  [adView setCenter:center];
  [mainView addSubview:adView];
  [window_ makeKeyAndVisible];
  [self playSong];
}

- (void)dealloc {
  [mainViewController_ release];
  [adViewController_ release];
  [window_ release];
  [nowPlayingText_ release];
  [super dealloc];
}

- (void)playAd {
  [[adViewController_ view] setHidden:NO];
  [[self nowPlayingText] setHidden:YES];

  // Play the loaded ad.
  [adViewController_ showLoadedGoogleAd];
}

#pragma mark GADAdViewControllerDelegate
- (UIViewController *)viewControllerForModalPresentation:
    (GADAdViewController *)adController {
  return mainViewController_;
}

// Set the ad click action to display the advertiser's site in a full-screen
// UIWebView.
- (GADAdClickAction)adControllerActionModelForAdClick:
    (GADAdViewController*)adController {
  return GAD_ACTION_DISPLAY_INTERNAL_WEBSITE_VIEW;
}

- (void)adController:(GADAdViewController*)adController
     failedWithError:(NSError*)error {
  // Handle error here.
}

- (void)loadFailed:(GADAdViewController*)adController
         withError:(NSError *)error {
  NSLog(@"loadFailed results:%@", [error localizedDescription]);
  adLoadFailed_ = YES;
  // Since the ad couldn't load, replay the song if it has already finished.
  if (songDone_) {
    [self playSong];
  }
}

- (void)loadSucceeded:(GADAdViewController*)adController
          withResults:(NSDictionary*)results {
  NSLog(@"loadSucceeded results:%@", results);
  adLoaded_ = YES;

  // The ad has loaded. If song is still playing, do nothing, otherwise
  // start the ad playing.
  if (songDone_) {
    [self playAd];
  }
}

- (void)showFailed:(GADAdViewController*)adController
         withError:(NSError*)error {
  NSLog(@"showFailed results:%@", [error localizedDescription]);

  // Since the ad couldn't play, play the song again.
  [self playSong];
}

- (void)showSucceeded:(GADAdViewController*)adController
          withResults:(NSDictionary*)results {
  NSLog(@"showSucceeded results:%@", results);

  // The ad has finished playing, so replay the song.
  [self playSong];
}

#pragma mark AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player
                       successfully:(BOOL)success {
  NSLog(@"NSAudio:audioPlayerDidFinishPlaying:successfully:%d", success);
  songDone_ = YES;

  // If the song is finished and the ad is ready, play it.
  if (adLoaded_) {
    [self playAd];
  } else if (adLoadFailed_) {
    [self playSong];
  } else {
    // Song finished but the ad has not finished loading. Play the song
    // again to avoid dead air.
    [self playSong];
  }
}

@end

